#微信自动回复
#coding=utf8
import itchat
import time
import requests
import json

# 自动回复
# 封装好的装饰器，当接收到的消息是Text，即文字消息
@itchat.msg_register('Text')
def text_reply(msg):
    # 当消息不是由自己发出的时候
    #if not msg['FromUserName'] == myUserName:
        # 发送一条提示给文件助手
        itchat.send_msg(u"[%s]收到好友@%s 的信息：%s\n" %
                        (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(msg['CreateTime'])),
                         msg['User']['NickName'],
                         msg['Text']), 'filehelper')
        # 回复给好友
        return getReturnMsg(msg['Text'])

#获取图灵自动答复
def getReturnMsg(message):
     res = requests.get("http://www.tuling123.com/openapi/api?key=c5a12866eef646c787c7f72ff9e9b9bf&info=%s&userid=",message)
     loadjosn=json.loads(res.text)
     return loadjosn['text']

#给指定好友发消息，消息内容和好友名称关键字
def sendMsgToUser(msg,_name):
        #查找符合用户的好友集合
        users=itchat.search_friends(name=_name)
        #获取好友的username，用户发送消息
        userName=users[0]['UserName']
        itchat.send(msg,toUserName=userName)

#给公众号发消息
def sendMsgToMps(msg,_name):
        #获取公众号列表
        mps=itchat.get_mps()
        #根据名称查找要发消息的公众号
        mps=itchat.search_mps(name=_name)   
        userName = mps[0]['UserName']
        itchat.send(msg,toUserName = userName) 

#给微信群发消息
def sendMsgToRooms(msg,_name):
        #获取微信群  
        rooms=itchat.get_chatrooms() 
        sendRoomName=''  
        for item in rooms:
                if item['NickName']==_name:
                        sendRoomName=item['UserName']
        
        itchat.send_msg(msg,sendRoomName)


if __name__ == '__main__':
    itchat.auto_login()
    # 获取自己的UserName
    myUserName = itchat.get_friends(update=True)[0]["UserName"]
    itchat.run()

